<template>
  <div class="bg-white overflow-hidden">
    <div class="form-title">企业融资经历</div>
    <el-form
      v-loading="formLoading"
      ref="financForm"
      :model="tempFormObj"
      label-width="0"
    >
      <table class="self-table-form" style="min-height: auto">
        <thead>
          <th v-for="item in headNameList" :key="item" class="m-label text-center">
            {{ item }}
          </th>
          <th class="m-label text-center">操作</th>
        </thead>
        <tbody>
          <tr v-for="(item, index) in tempFormObj.financForm" :key="item.id">
            <td class="m-label text-center w-16">
              {{ index + 1 }}
            </td>
            <td class="label-error relative">
              <!-- <div
                :class="[
                  'absolute left-2 bottom-0 transition-all duration-200 text-xs text-red-500 z-10',
                  !item.time ? 'visible' : 'invisible'
                ]"
              >
                此项为必须输入项
              </div> -->
              <el-form-item
                :prop="'financForm.' + index + '.time'"
                :rules="{
                  required: true,
                  message: '请选择投资时间',
                  trigger: 'blur',
                }"
                style="width: 7.5rem"
              >
                <el-date-picker
                  v-model="item.time"
                  align="center"
                  type="date"
                  prefix-icon="el-icon"
                  placeholder="选择日期"
                  :picker-options="pickerOptions"
                  style="width: 100%"
                >
                </el-date-picker>
              </el-form-item>
            </td>
            <td class="w-28">
              <el-form-item
                :prop="'financForm.' + index + '.rounds'"
                :rules="{
                  required: true,
                  message: '请选择投资轮次',
                  trigger: 'change',
                }"
              >
                <el-select
                  v-model="item.rounds"
                  filterable
                  placeholder="请选择"
                  style="width: 60px"
                >
                  <el-option
                    v-for="item in financTypeOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </td>
            <td class="w-64">
              <el-form-item
                :prop="'financForm.' + index + '.name'"
                :rules="formRules.name"
              >
                <el-input type="text" v-model="item.name"></el-input>
              </el-form-item>
            </td>
            <td class="w-48">
              <el-form-item
                :prop="'financForm.' + index + '.money'"
                :rules="formRules.money"
              >
                <el-input-number
                  v-model="item.money"
                  auto-complete="off"
                  :controls="false"
                  class="m-input-number"
                ></el-input-number>
              </el-form-item>
            </td>
            <td class="w-48">
              <el-form-item
                :prop="'financForm.' + index + '.trueMoney'"
                :rules="formRules.trueMoney"
              >
                <el-input-number
                  v-model="item.trueMoney"
                  auto-complete="off"
                  :controls="false"
                  class="m-input-number"
                ></el-input-number>
              </el-form-item>
            </td>
            <td class="w-48">
              <el-form-item
                :prop="'financForm.' + index + '.valuation'"
                :rules="formRules.valuation"
              >
                <el-input-number
                  v-model="item.valuation"
                  auto-complete="off"
                  :controls="false"
                  class="m-input-number"
                ></el-input-number>
              </el-form-item>
            </td>
            <td class="w-44">
              <el-form-item
                :prop="'financForm.' + index + '.proportion'"
                :rules="formRules.proportion"
              >
                <el-input-number
                  v-model="item.proportion"
                  auto-complete="off"
                  :controls="false"
                  class="m-input-number"
                  @input="handlePropInput(item.id, index)"
                ></el-input-number>
              </el-form-item>
            </td>

            <!-- <td>
              <a
                class="text-blue-500 alink"
                target="_blank"
                :href="item.capitalFile.url"
              >
                {{ item.capitalFile.name }}
              </a>
            </td>
            <td>
              <a
                class="text-blue-500 alink"
                wtarget="_blank"
                :href="item.equityChangeFiel.url"
              >
                {{ item.equityChangeFiel.name }}
              </a>
            </td>
            <td>
              <a
                class="text-blue-500 alink"
                target="_blank"
                :href="item.capitalAccount.url"
              >
                {{ item.capitalAccount.name }}
              </a>
            </td> -->
            <td>
              <div class="flex justify-center">
                <el-button
                  class="m-auto"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteFormItem(item.id)"
                >
                </el-button>
              </div>
            </td>
          </tr>
          <tr>
            <td :colspan="headNameList.length + 1">
              <div class="flex justify-start">
                <el-button class="ml-0" type="primary" @click="addFormItem">
                  添加记录
                </el-button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>

      <div class="flex justify-between py-10 text-center">
        <el-button
          v-if="isSubmit"
          class="confirm-btn tracking-widest"
          type="primary"
          size="medium"
          @click="submitForm"
        >
          保存 / 下一步
        </el-button>

        <DeclareNextItem ref="next" v-show="false" />
      </div>
    </el-form>
  </div>
</template>

<script>
import { checNumber, limitLength } from "@/utils/formRules.js";
import { saveFinanc } from "@/api/declareForm/financ";

export default {
  name: "EnterpriseFinancForm",
  props: {
    sourceList: {
      type: Array,
      default: [],
    },
    isSubmit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    var checkProportion = (rule, value, callback) => {
      if (!value || value > 100 || value < 0) {
        return callback(new Error("请输入有效值"));
      }
      let nowProption = 0;
      this.tempFormObj.financForm.forEach((item) => {
        nowProption += Number(item.proportion);
      });
      if (nowProption > 100) {
        return callback(new Error("所填比例 大于 剩余比例"));
      } else {
        return callback();
      }
    };

    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      formLoading: false,
      // 投资轮次 类型数组
      financTypeOptions: [
        // {
        //   dictValue: "0",
        //   dictLabel: "天使轮"
        // },
        // {
        //   dictValue: "1",
        //   dictLabel: "A轮"
        // },
        // {
        //   dictValue: 2,
        //   dictLabel: "B轮"
        // },
        // {
        //   dictValue: 3,
        //   dictLabel: "C轮"
        // },
        // {
        //   dictValue: 4,
        //   dictLabel: "D轮"
        // }
      ],

      headNameList: [
        "序号",
        "投资时间",
        "投资轮次",
        "投资机构名称",
        "协议投资金额（万元）",
        "实际投资金额（万元）",
        "融资后估值（万元）",
        "占股比例（％）",
        // "验资证明",
        // "股权变更证明",
        // "资金到账证明"
      ],
      modleFormObj: {
        id: -1,
        time: "",
        rounds: "",
        name: "",
        money: 0,
        trueMoney: 0,
        valuation: 0,
        proportion: 0,
      },
      tempFormObj: {
        financForm: [
          // {
          // id: 0,
          // time: "",
          // rounds: "",
          // name: "投资机构名称",
          // money: 100,
          // valuation: 100,
          // proportion: 20
          // capitalFile: {
          //   url: "https://www.tailwindcss.cn/docs/overflow",
          //   name: "验资证明.pdf"
          // },
          // equityChangeFiel: {
          //   url: "https://www.tailwindcss.cn/docs/overflow",
          //   name: "股权变更证明.pdf"
          // },
          // capitalAccount: {
          //   url: "https://www.tailwindcss.cn/docs/overflow",
          //   name: "资金到账证明.pdf"
          // }
          // }
        ],
      },
      formRules: {
        name: [
          { required: true, message: "请输入投资机构名称", trigger: "blur" },
          {
            validator: limitLength(30),
            trigger: "blur",
          },
        ],
        money: [
          {
            validator: limitLength(10),
            trigger: "blur",
          },
          {
            validator: checNumber,
            trigger: "blur",
          },
        ],

        trueMoney: [
          {
            validator: limitLength(10),
            trigger: "blur",
          },
          {
            validator: checNumber,
            trigger: "blur",
          },
        ],
        valuation: [
          {
            validator: limitLength(10),
            trigger: "blur",
          },
          {
            validator: checNumber,
            trigger: "blur",
          },
        ],
        proportion: [
          {
            validator: checNumber,
            trigger: "blur",
          },
          {
            validator: limitLength(10),
            trigger: "blur",
          },
          {
            validator: checkProportion,
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    sourceList(v) {
      if (v) {
        // v.forEach(item=>{
        //   let tempObj = {}
        // })
        this.tempFormObj.financForm = v;

        // this.empFormObj.financForm["list"] = v.stockRightList;
      }
    },
  },
  created() {
    this.initDictFileType();
  },
  methods: {
    initDictFileType() {
      this.getDicts("declare_invest_type").then((res) => {
        if (res.code == 200) {
          this.financTypeOptions = res.data;
        }
      });
    },
    initRelationId() {
      let realationId = this.$route.query.id;
      if (realationId) {
        this.modleFormObj.relationId = parseInt(realationId);
      }
    },
    addFormItem() {
      let timeChuo = new Date();
      let addObj = JSON.parse(JSON.stringify(this.modleFormObj));
      addObj["id"] = timeChuo.valueOf();
      this.tempFormObj.financForm.push(addObj);
    },
    deleteFormItem(id) {
      let tempArr = JSON.parse(JSON.stringify(this.tempFormObj.financForm));
      let newArr = tempArr.filter((item) => {
        return item.id !== id;
      });
      this.tempFormObj.financForm = newArr;
    },
    /**
     * @function handlePropInput
     * @param id [number]: 股东信息数组 唯一key id
     *        index [nubmer]: 股东信息数组 索引
     * @description 表单项股东持有股份 输入
     */
    handlePropInput(id, index) {
      let canMaxProption = 0;
      this.tempFormObj.financForm.forEach((item) => {
        if (item.id !== id) {
          canMaxProption += Number(item.proportion);
        }
      });

      canMaxProption = 100 - canMaxProption < 0 ? 0 : 100 - canMaxProption;
      let inputV = this.tempFormObj.financForm[index]["proportion"];

      if (isNaN(Number(inputV))) {
        this.tempFormObj.financForm[index]["proportion"] = 0;
      }
      if (inputV < 0) {
        this.tempFormObj.financForm[index]["proportion"] = 0;
      }
      if (inputV > canMaxProption) {
        this.$message({
          type: "error",
          message: "所填比例 大于 剩余比例",
        });
        this.tempFormObj.financForm[index]["proportion"] = 0;
      }
    },

    submitForm() {
      let formName = "financForm";
      let resFrom = this.tempFormObj.financForm;
      this.$refs["financForm"].validate((valid) => {
        let resquestObj = {
          relationId: parseInt(this.$route.query.id),
          list: [],
        };
        if (valid) {
          this.formLoading = true;

          resquestObj["list"] = resFrom;
          saveFinanc(resquestObj).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "保存成功",
              });
              // 跳转至下一页
              this.$refs.next.nextDeclareItem();
            } else {
              this.$message.error(res.msg);
            }
            this.formLoading = false;
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.m-input-number {
  width: 100%;

  ::v-deep .el-input__inner {
    text-align: left;
  }
}
</style>
